// 该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
// 引入组件
import About from "../pages/About";
import Home from "../pages/Home";
import News from "../pages/News";
import Message from "../pages/Message";
import Detail from "../pages/Detail";

// 创建并暴露一个路由器
const router = new VueRouter({
  routes: [
    // 一级路由
    {
      // 命名路由
      name: "guanyu",
      path: "/about",
      component: About,
      meta: {
        title: "关于",
      },
    },
    {
      name: "zhuye",
      path: "/home",
      component: Home,
      meta: {
        // meta配置项中保存一些自定义数据
        title: "主页",
      },
      // 二级路由 children
      children: [
        {
          // 二级路由path不以 / 开头
          name: "xinwen",
          path: "news",
          component: News,
          meta: { isAuth: true, title: "新闻" }, // 需要进行权限校验
        },
        {
          name: "xiaoxi",
          path: "message",
          component: Message,
          meta: { isAuth: true, title: "消息" }, // 需要进行权限校验
          // 三级路由
          children: [
            {
              // 命名路由
              name: "xiangqing",
              path: "detail/:id/:title", // 使用占位符声明接收paramas参数
              component: Detail,
              meta: { title: "详情" },

              props($route) {
                return {
                  id: $route.params.id,
                  title: $route.params.title,
                };
              },
            },
          ],
        },
      ],
    },
  ],
});

// 全局前置路由守卫 在初始化,每一次路由切换前被调用,一般用于权限校验(cook,session,token)
router.beforeEach((to, from, next) => {
  console.log("前置路由守卫", from, to);
  // from:存储当前路由信息 to:存储要跳转路由的信息
  // 动态决定是否路由跳转
  if (to.meta.isAuth) {
    // 判断是否需要权限校验
    if (localStorage.getItem("school") === "atguigu") {
      next(); // 进行路由跳转
    } else {
      alert("请先登录!!");
    }
  } else {
    next();
  }
});

// 后置路由守卫 在初始化时,每次路由切换后被调用
router.afterEach((to, from) => {
  console.log("后置路由守卫", from, to);
  // 当路由成功切换后再执行
  document.title = to.meta.title || "Vue"; // 将浏览器标题改为当前路由的title
});

export default router;
